#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdio>
#include <cstring>
#include <thread>
#include<unistd.h>
#include "Log.hpp"
void Usage(std::string path)
{
    std::cout << "\nUsage: " << path << " server_ip server_port\n"
              << std::endl;
}
int main(int argc, char *argv[])
{
    // 客户端不需要bind，不需要显示的bind，但是一定是需要port
    // 需要让os自动进行port选择
    // 客户端需要连接别人的能力
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    bool alive = false;
    int sock = 0;
    std::string line;
    while (true)
    {
        if (!alive)
        {
            // 创建套接字
            sock = socket(AF_INET, SOCK_STREAM, 0);
            if (sock < 0)
            {
                logMessage(FATAL, "%s", "sock error");
                exit(2);
            }
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(server_port);
            server.sin_addr.s_addr = inet_addr(server_ip.c_str());
            // 建立链接
            if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0)
            {
                logMessage(FATAL, "%s", "connect fail");
                exit(3);
            }
            //logMessage(NORMAL, "%s", "connect success");
            alive = true;
        }
        std::cout<<"请输入：";
        std::getline(std::cin,line);
        if(line == "quit")
            break;
        ssize_t s = send(sock,line.c_str(),line.size(),0);
        if(s>0)
        {
            char buffer[1024];
            ssize_t r = recv(sock,buffer,sizeof(buffer)-1,0);
            if(r>0)
            {
                buffer[r]=0;
                std::cout<<buffer<<std::endl;
            }
            else if(r==0)
            {
                alive =false;
                close(sock);
            }
        }
        else{
            alive = false;
            close(sock);
        }
    }

    return 0;
}